package com.mxfcode.back.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mxfcode.back.dto.UserDTO;
import com.mxfcode.back.dto.UserSearchDTO;
import com.mxfcode.back.mapper.UserMapper;
import com.mxfcode.back.service.UserService;
import com.mxfcode.bbs_common.date.DateUtils;
import com.mxfcode.bbs_common.response.PageDataResult;
import com.mxfcode.bbs_common.util.aes.AESUtil;
import com.mxfcode.bbs_common.util.community.CommunityConstant;
import com.mxfcode.bbs_common.util.community.CommunityUtil;
import com.mxfcode.front.bbs_login.mapper.LoginMapper;
import com.mxfcode.common.HostHolder;
import com.mxfcode.entity.TSUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @类名 UserServiceImpl
 * @描述 用户管理业务
 * @作者 mxf
 * @创建日期 2021-03-05 14:02
 **/
@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private LoginMapper loginMapper;


    @Override
    public PageDataResult getUserList(UserSearchDTO userSearch, Integer pageNum, Integer pageSize) {
        PageDataResult pageDataResult = new PageDataResult();
        List<UserDTO> users = userMapper.getUserList(userSearch);

        PageHelper.startPage(pageNum, pageSize);

        if(users.size() != 0){
            PageInfo<UserDTO> pageInfo = new PageInfo<>(users);
            pageDataResult.setList(users);
            pageDataResult.setTotals((int) pageInfo.getTotal());
        }

        return pageDataResult;
    }

    @Override
    public Map<String, Object> addUser(TSUser user) {
        Map<String,Object> data = new HashMap();
        try {
            TSUser old = userMapper.getUserByUserName(user.getUserName(),null);
            if(old != null){
                data.put("code",0);
                data.put("msg","用户名已存在！");
                logger.error("用户[新增]，结果=用户名已存在！");
                return data;
            }

            String username = user.getUserName();
            if(user.getPassword() == null){
                String password = AESUtil.aesEncrypt("123456", CommunityConstant.ASE_KEY);
                user.setPassword(password);
            }else{
                String password = AESUtil.aesEncrypt(user.getPassword(), CommunityConstant.ASE_KEY);
                user.setPassword(password);
            }

            user.setCreateDate(DateUtils.getCurrentDateToDate());
            user.setCreateBy(hostHolder.getUser().getUserName());
            user.setCreateName(hostHolder.getUser().getRealName());
            user.setUserStatus(1);
            user.setId(CommunityUtil.generateUUID());
            user.setType(0);
            user.setStatus(1);
            user.setActivationCode(CommunityUtil.generateUUID());
            user.setAvatarUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
            user.setCreateDate(new Date());
            int result = loginMapper.insertUser(user);
            if(result == 0){
                data.put("code",0);
                data.put("msg","新增失败！");
                logger.error("用户[新增]，结果=新增失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","新增成功！");
            logger.info("用户[新增]，结果=新增成功！");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户[新增]异常！", e);
            return data;
        }
        return data;
    }

    @Override
    public Map<String, Object> updateUser(TSUser user) throws Exception {
        Map<String,Object> data = new HashMap();
        String id = user.getId();
        TSUser old = userMapper.getUserByUserName(user.getUserName(),id);
        if(old != null){
            data.put("code",0);
            data.put("msg","用户名已存在！");
            logger.error("用户[更新]，结果=用户名已存在！");
            return data;
        }
        String username = user.getUserName();
        if(user.getPassword() != null){
            String password = AESUtil.aesEncrypt(user.getPassword(), CommunityConstant.ASE_KEY);
            user.setPassword(password);
        }

        int result = userMapper.updateUser(user);
        if(result == 0){
            data.put("code",0);
            data.put("msg","更新失败！");
            logger.error("用户[更新]，结果=更新失败！");
            return data;
        }
        data.put("code",1);
        data.put("msg","更新成功！");
        logger.info("用户[更新]，结果=更新成功！");
        return data;
    }

    @Override
    public Map<String, Object> delUser(String id, Integer status) {
        Map<String, Object> data = new HashMap<>();
        try {
            // 删除用户
            int result = userMapper.updateUserStatus(id,status);
            if(result == 0){
                data.put("code",0);
                data.put("msg","删除用户失败");
                logger.error("删除用户失败");
                return data;
            }
            data.put("code",1);
            data.put("msg","删除用户成功");
            logger.info("删除用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除用户异常！", e);
        }
        return data;
    }

    @Override
    public Map<String, Object> recoverUser(String id, Integer status) {
        Map<String, Object> data = new HashMap<>();
        try {
            int result = userMapper.updateUserStatus(id,status);
            if(result == 0){
                data.put("code",0);
                data.put("msg","恢复用户失败");
            }
            data.put("code",1);
            data.put("msg","恢复用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("恢复用户异常！", e);
        }
        return data;
    }

    @Override
    public Map<String, Object> update(TSUser user) {
        Map<String, Object> data = new HashMap<>();
        try {
            int result = userMapper.update(user);
            if(result == 0){
                data.put("code",0);
                data.put("msg","更新失败");
            }
            data.put("code",1);
            data.put("msg","更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更新异常！", e);
        }
        return data;
    }
}
